<!--
Copyright 2014 The Chromium Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->

<link rel="import" href="ct-builder-list.html">
<link rel="import" href="ct-commit-list.html">
<link rel="import" href="ct-failure-group-data.html">

<script>
function CTStepFailureGroupData(failures, commitList, suspectedCLsByRepo) {
  this.failures = failures;
  this.key = failures.map(function(failure) {
    return failure.key;
  }).join('::');
  this.commitList = commitList;
  this.suspectedCLsByRepo = suspectedCLsByRepo;
  this.builderList = new CTBuilderList(failures);
  this.category = 'step';
};

CTStepFailureGroupData.prototype.getAnnotations = function() {
  return this.failures.map(function(failure) {
    return failure.annotations();
  }).flatten();
};

CTStepFailureGroupData.prototype.failureKeys = function() {
  return this.failures.map(function(failure) {
    return failure.keys();
  }).flatten();
};

CTStepFailureGroupData.prototype.isTreeCloser = function() {
  return this.failures.any(function(failure) {
    return failure.isTreeCloser();
  });
};

CTStepFailureGroupData.prototype.failedOnce = function() {
  if (!this.failures.length)
    return false;

  for (var i = 0; i < this.failures.length; i++) {
    var totalFailures = 0;
    var resultNodes = this.failures[i].resultNodesByBuilder;
    for (var r in resultNodes) {
      totalFailures += resultNodes[r].failingBuildCount;
      if (totalFailures > 1)
        return false;
    }
  }
  return true;
};

CTStepFailureGroupData.prototype.fileBugMessage = function() {
  var message = '';
  this.failures.forEach(function(failure) {
    message += failure.step;
    if (failure.testName) {
      message += ' ' + failure.testName + '\n';
      message += failure.flakinessDashboardURL(this.tree);
    }
    message += '\n';
  });
  message += '\nRevision range:\n';
  this.commitList.repositories.forEach(function(repository) {
    message += repository.name + ' ' + repository.range + '\n';
  });
  message += '\nFailing builders:\n';
  this.builderList.builders.forEach(function(builder) {
    message += builder.builder + ': ' + builder.buildUrl + '\n';
  });

  return message;
};

CTStepFailureGroupData.prototype.fileBugLink = function() {
  return CTFailureGroupData.fileBugLink('Build failure',
      'Build is broken:\n' + this.fileBugMessage(), this.bugLabels);
};
</script>
